package reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class FieldDemo01 {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        //获取类的字节码对象
        Class<Rectangle> rectangleClass = Rectangle.class;
        //获取指定构造方法，包括私有方法
        Constructor<Rectangle> constructor =
                rectangleClass.getDeclaredConstructor(int.class,int.class);
        //通过反射构建对象实例
        constructor.setAccessible(true);//设置私有方法可访问
        Rectangle rectangle =constructor.newInstance(10,20);
        //获取类中的length属性并修改它的值为20，然后在计算周长
        Field f1=rectangleClass.getDeclaredField("length");
        f1.setAccessible(true);//设置私有属性可访问
        f1.set(rectangle,20);//为rectangle对象的f1属性赋值为20
        //获取矩形周长
        int tPerimeter=rectangle.getPerimeter();
        System.out.println("矩形周长："+tPerimeter);
    }
}
